import 'dart:convert';

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:hkzf/model.dart';
import 'package:hkzf/model/user.dart';
import 'package:hkzf/utils/common_toast.dart';
import 'package:hkzf/utils/dio_http.dart';
import 'package:hkzf/utils/store.dart';
import 'package:hkzf/utils/string_is_null_or_empty.dart';
import 'package:provider/provider.dart';

class LoginPage extends StatefulWidget {
  LoginPage({
    Key key,
  }) : super(key: key);
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool _showPassword = false;
  var usernameController = TextEditingController();
  var passwordController = TextEditingController();
  Map arg; //路由传入参数：redirect

  // 登录方法
  void login() async {
    var username = usernameController.text;
    var password = passwordController.text;
    if (stringIsNullOrEmpty(username) || stringIsNullOrEmpty(password)) {
      CommonToast.showToast('账号或密码不能为空');
      return;
    }
    var res = await DioHttp.of(context).post('/api/v1/auth/login', params: {
      'username': username,
      'password': password,
    });
    if (res == null) {
      return;
    }
    if (res['code'] == 200) {
      // 保存token到缓存和provider中
      var token = res['data']['token'];
      Map<String, dynamic> userInfo = res['data']['user'];
      userInfo.forEach((key, value) {
        userInfo[key] = value.toString();
      });
      Provider.of<UserInfo>(context, listen: false).setToken(token);
      Provider.of<UserInfo>(context, listen: false).setUserInfo(userInfo);
      var store = await Store.getInstance();
      store.setString(StoreKeys.token, token);
      store.setMap(StoreKeys.userInfo, userInfo);
      if (arg != null && arg['redirect'] != null) {
        RouteSettings redirect = arg['redirect'];
        // Router().navigateTo(context, redirect.name,clearStack:true);
        Navigator.of(context).pushNamedAndRemoveUntil(
            redirect.name, ModalRoute.withName('/login'),
            arguments: redirect.arguments);
      } else {
        Navigator.of(context).pop();
      }
      // var userRes = await DioHttp.of(context).get('/api/v1/auth/user');
      // if (userRes == null) {
      //   return;
      // }
      // if (userRes['code'] == 200) {
      //   print(userRes);
      //   // Provider.of<UserInfo>(context, listen: false).setUserInfo(userInfo);
      //   // 重定向跳转
      //   return;
      //   if (arg != null && arg['redirect'] != null) {
      //     RouteSettings redirect = arg['redirect'];
      //     // Router().navigateTo(context, redirect.name,clearStack:true);
      //     Navigator.of(context).pushNamedAndRemoveUntil(
      //         redirect.name, ModalRoute.withName('/login'),
      //         arguments: redirect.arguments);
      //   } else {
      //     Navigator.of(context).pop();
      //   }
      // }
    }
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    arg = ModalRoute.of(context).settings.arguments;
    return Scaffold(
        appBar: AppBar(
          title: Text('登录'),
        ),
        body: SafeArea(
          minimum: EdgeInsets.all(30),
          child: ListView(
            children: <Widget>[
              Column(
                children: [
                  TextField(
                    controller: usernameController,
                    decoration:
                        InputDecoration(hintText: '请输入用户名', labelText: '用户名'),
                  ),
                  Padding(
                    padding: EdgeInsets.all(10),
                  ),
                  TextField(
                    controller: passwordController,
                    decoration: InputDecoration(
                        hintText: '请输入密码',
                        labelText: '密码',
                        suffixIcon: IconButton(
                            icon: Icon(_showPassword
                                ? Icons.visibility_off
                                : Icons.visibility),
                            onPressed: () {
                              setState(() {
                                _showPassword = !_showPassword;
                              });
                            })),
                    obscureText: !_showPassword,
                  ),
                  Padding(
                    padding: EdgeInsets.all(10),
                  ),
                  Container(
                    width: double.infinity,
                    child: RaisedButton(
                      onPressed: () {
                        login();
                      },
                      color: Colors.green,
                      child: Text(
                        '登录',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                  Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                    Text('还没有账号,'),
                    FlatButton(
                      onPressed: () {
                        Navigator.pushReplacementNamed(context, '/register');
                      },
                      child: Text(
                        '去注册~',
                        style: TextStyle(color: Colors.green),
                      ),
                    )
                  ])
                ],
              ),
            ],
          ),
        ));
  }
}
